// store/user.ts 改进版
import { StoreOptions } from "vuex";
import ACCESS_ENUM from "@/access/accessEnum";
import { UserControllerService } from "../../generated";

export default {
  namespaced: true,
  state: () => ({
    loginUser: {
      userName: "未登录",
      userRole: ACCESS_ENUM.NOT_LOGIN,
    },
    loginChecked: false, // 新增标志，表示是否已经检查过登录状态
    loading: false, // 新增加载状态
    isLogout: false, // 新增标志，表示用户是否主动退出登录
  }),
  actions: {
    async getLoginUser({ commit, state }) {
      // 如果用户已经主动退出，则不自动登录
      if (state.isLogout) {
        return;
      }

      // 如果已经在加载中，则不重复请求
      if (state.loading) {
        return;
      }

      // 如果已经验证过且是登录状态，则不重复请求
      if (
        state.loginChecked &&
        state.loginUser.userRole !== ACCESS_ENUM.NOT_LOGIN
      ) {
        return;
      }

      commit("setLoading", true);
      try {
        // 从远程请求获取登录信息
        const res = await UserControllerService.getLoginUserUsingGet();
        if (res.code === 0) {
          commit("updateUser", res.data);
          commit("setIsLogout", false); // 重置退出标志
          // 保存到本地存储以保持登录状态
          localStorage.setItem("loginUser", JSON.stringify(res.data));
          localStorage.setItem("isLogout", "false");
        } else {
          commit("updateUser", {
            userName: "未登录",
            userRole: ACCESS_ENUM.NOT_LOGIN,
          });
          localStorage.removeItem("loginUser");
        }
      } catch (error) {
        console.error("获取登录用户信息失败", error);
        // 错误时也更新状态为未登录
        commit("updateUser", {
          userName: "未登录",
          userRole: ACCESS_ENUM.NOT_LOGIN,
        });
        localStorage.removeItem("loginUser");
      } finally {
        commit("setLoginChecked", true);
        commit("setLoading", false);
      }
    },

    // 初始化用户状态，从本地存储恢复
    initUser({ commit }) {
      // 检查用户是否主动退出登录
      const isLogoutStr = localStorage.getItem("isLogout");
      if (isLogoutStr === "true") {
        commit("setIsLogout", true);
        commit("updateUser", {
          userName: "未登录",
          userRole: ACCESS_ENUM.NOT_LOGIN,
        });
        commit("setLoginChecked", true);
        return;
      }

      const userStr = localStorage.getItem("loginUser");
      if (userStr) {
        try {
          const savedUser = JSON.parse(userStr);
          commit("updateUser", savedUser);
        } catch (e) {
          localStorage.removeItem("loginUser");
        }
      }
      commit("setLoginChecked", true);
    },

    async logout({ commit }) {
      // 标记用户已主动退出登录
      commit("setIsLogout", true);
      localStorage.setItem("isLogout", "true");

      // 清除用户状态
      commit("updateUser", {
        userName: "未登录",
        userRole: ACCESS_ENUM.NOT_LOGIN,
        id: undefined,
        userAccount: undefined,
        userAvatar: undefined,
        userProfile: undefined,
      });

      // 重置登录检查状态
      commit("setLoginChecked", false);

      // 清除所有本地存储(保留isLogout标记)
      localStorage.removeItem("loginUser");
      localStorage.removeItem("user");
      sessionStorage.removeItem("loginUser");
      sessionStorage.removeItem("user");

      // 删除所有可能包含用户信息的 cookie
      const cookies = document.cookie.split(";");
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i];
        const eqPos = cookie.indexOf("=");
        const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie =
          name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/";
      }
    },

    // 明确用户登录动作
    setUserLogin({ commit }) {
      commit("setIsLogout", false);
      localStorage.setItem("isLogout", "false");
    },
  },
  mutations: {
    updateUser(state, payload) {
      state.loginUser = payload;
    },
    setLoginChecked(state, payload) {
      state.loginChecked = payload;
    },
    setLoading(state, payload) {
      state.loading = payload;
    },
    setIsLogout(state, payload) {
      state.isLogout = payload;
    },
  },
} as StoreOptions<any>;
